package com.gegong.vmware.workstation;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gegong.vmware.workstation.exceptions.RestApiAccessException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import okhttp3.Response;

import java.io.IOException;
import java.util.List;

public class RestResponse {

    private Response response;
    private String responseBodyString;

    public RestResponse(VMwareWorkstationManagementActions.BaseAction action, Response response)
            throws IOException, AssertionError, RestApiAccessException {
        this.response = response;
        assert response.body() != null;
        responseBodyString = response.body().string();
        if (!response.isSuccessful())
            throw new RestApiAccessException(action, getErrorData());
    }

    @EqualsAndHashCode(callSuper = false)
    @Data
    public static class ErrorResponse extends JsonBody {

        private int code;
        private String message;
    }


    public <T> List<T> getListData(Class<T> t) {
        return JSONArray.parseArray(responseBodyString, t);
    }


    public <T> T getData(Class<T> t) {
        return JSONObject.parseObject(responseBodyString, t);
    }

    public ErrorResponse getErrorData() {

        return getData(ErrorResponse.class);
    }


}
